var supportEngines = supportEngines;
var supportCharSets = supportCharSets;

var engineDataArray = [];
var charSetDataArray = [];
Ext.each(supportEngines , function(row) {
    engineDataArray.push({data:row,label:row});
});
Ext.each(supportCharSets , function(row) {
    charSetDataArray.push({data:row,label:row});
});
var rowFormatDataArray = [
    {data:'COMPACT' , label:'COMPACT'},
    {data:'COMPRESSED' , label:'COMPRESSED'},
    {data:'DEFAULT' , label:'DEFAULT'},
    {data:'DYNAMIC' , label:'DYNAMIC'},
    {data:'FIXED' , label:'FIXED'},
    {data:'REDUNDANT' , label:'REDUNDANT'}
];
var rowFormatForTokuDBEngine = [
    {data:'TOKUDB_ZLIB' , label:'<b>TOKUDB_ZLIB</b> 启用zlib压缩，压缩效果偏中，CPU消耗偏中，建议使用(默认)'},
    {data:'TOKUDB_QUICKLZ' , label:'<b>TOKUDB_QUICKLZ</b> 启用quicklz压缩，压缩效果差，CPU消耗低'},
    {data:'TOKUDB_LZMA' , label:'<b>TOKUDB_LZMA</b> 启用lzma压缩，压缩效果好，CPU消耗高'}
];
var insertMethodDataArray = [
    {data:'FIRST' , label:'FIRST'},
    {data:'LAST' , label:'LAST'},
    {data:'NO' , label:'NO'}
];
var okOrNoDataArray = [
    {data:'yes' , label:'Y'},
    {data:'no' , label:'N'}
];
var packKeysDataArray = [
    {data:'DEFAULT' , label:'DEFAULT'},
    {data:'0' , label:'0'},
    {data:'1' , label:'1'}
];

var referenceOptionArray = [
    {"data" : "RESTRICT"},
    {"data" : "NO ACTION"},
    {"data" : "CASCADE"},
    {"data" : "SET NULL"}
];
var dbVersionNum = dbVersionNum;
var dbVersion5_6 = dbVersion5_6;

if(dbVersionNum && dbVersionNum != 'null') {
    dbVersionNum = parseInt(dbVersionNum);
}
var isMoreOrEqual5_6Version = (dbVersionNum >= dbVersion5_6);
var TABLE_CARD_PANEL;
function setActiveTab(i) {
    TABLE_CARD_PANEL.getLayout().setActiveItem(i);
}
Ext.onReady(function() {
    var baseInfoPanel ,
        columnPanel ,
        indexPanel ,
        referencePanel,
        partitionPanel;
    var viewSQL = function() {
        viewSQLOrSubmit(false);
    };
    var viewSQLOrSubmit = function(submit) {
        if(!baseInfoPanel.getForm().findField('tableName').getValue()) {
        	if(document.getElementById("base").className != "active"){
        		var win = new Ext.Window({
        			title: "请输入表名",
                    modal:true,
        			width: 500, 
        			height: 150, 
        			constrain: true, 
        			layout: "fit",
        			items:
        				inputTableNamePanel = new IDB.FormPanel({
        					defaults:{
        						autoFitErrors:false,//自动调整错误提示时候的宽度
        						labelSeparator:' : ',
        						width:450,
        						labelAlign :'right'
        					},
        					items:
        						[
                               		{
                               			padding:'20 0 0 0',
                               			fieldLabel:'<span style="color: red">*</span> 表名',
                               			allowBlank:false,
                               			name:'inputTableName',
                               			blankText:'表名不能为空，请输入',
                               			xtype:'textfield'
                               		}
                               	],                       
                            buttons:
                            	[
                		         	{
                		         		width: 50,
                		         		text : '确定',
                		         		xtype: 'button',
                		         		listeners: {
                		         			click: function() {
                		         				var inputTableNameItem = inputTableNamePanel.getForm().findField('inputTableName');
                		         				if(!inputTableNameItem.getValue()){
                		         					inputTableNameItem.focus();
                		         					inputTableNameItem.blur();
                		         				}else{
                		         					baseInfoPanel.getForm().findField('tableName').setValue(inputTableNameItem.getValue());
                		         					win.hide();
                		         					viewSQLOrSubmit(true);
                		         				}
                		         			}
                		         		}
                		         	}
                		       ]
                		 	})
        				}
        			);
        		win.show();
        		return;
        	}else {
                return $.message.warning('表名称不能为空。');
        	}
        }
        var params = baseInfoPanel.getValues();
        if(objectName) {
            params.oldTableName = objectName;
        }
        var columnArray = columnPanel.getAllRows();
        if(!columnArray) {
            setActiveId('column');
            return cardPanel.getLayout().setActiveItem(0);
        }
        params.columns = jsonToString(columnArray);
        params.indexes = jsonToString(indexPanel.getAllRows());
        params.partitionContent = partitionPanel.getPartitionContent();
        params.references = jsonToString(referencePanel.getAllRows());
        params.forSubmit = submit;
        params.dbName = nowDBName;
        params.dbVersionNum = dbVersionNum;
        params['dbType'] = now_db_type; 
        Ext.getBody().mask('正在生成执行脚本....');
        var url = getRoot()+'/dataManage/showAddTableScript';
        $.post(url,params,function(json){
        	Ext.getBody().unmask();
        	if(json.success) {
                var resultArray = json.root;
                var content = '';
                Ext.each(resultArray , function(row) {
                    content += Ext.String.trim(row) + ";\n";
                });
                showScript(submit ,content , params , resultArray);
            }
        	if(json.failure){
        		Ext.getBody().unmask();
        		$.feedbackMessage({
                    type: 'danger',
                    message: json.root
                });
        	}
        });
    };
    var viewCreateSQL = function() {
        Ext.getBody().mask('正在获取创建语句....');
        ajax({
            url:'/dataManage/table/showCreateTableLike',
            params:{tableName:objectName,dbName:nowDBName},
            success:function(resp) {
                Ext.getBody().unmask();
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    var sqlArea = new Ext.ux.form.field.CodeMirror({value:json.root});
                    var win = new IDB.Window({
                        title:'创建语句',
                        width:700,
                        height:450,
                        closable:true,
                        layout:'fit',
                        maximizable:true,
                        items:[sqlArea]
                    });
                }else {
                    $.message.error(json.root);
                }
            },
            failure:function() {
            	Ext.getBody().unmask();
            }
        });
    };
    var showScript  = function(submit , content , params , resultArray) {
        var appendButton = new Ext.Button({text:'确定',handler:function() {
            var value = sqlArea.getValue();
            win.getEl().mask('正在提交并执行变更信息.....');
            var url = getRoot() + '/dataManage/executeScript';
            params.script = resultArray[0];
            params.dbName = nowDBName;
            params.databaseId = dataBase_id;
            params.datasourceId = dataSource_id;
            params.dataSource = data_source;
            params.baseType = now_db_type;
            params.isLocal = isLocal;
            $.post(url,params,function(data){
            	win.getEl().unmask();
            	if(data.success){
            		win.close();
            		$.feedbackMessage({
                        type: 'success',
                        message: data.root,
                        showTime:5000
                    });
            		setTimeout(function() {
                        if(window.parent) {
                            if(window.onunload) {
                                window.onunload = null;
                            }
                            if(window.onbeforeunload) {
                                window.onbeforeunload = null;
                            }
                            window.parent.refreshTabCallBack(tabId , params['tableName'] , objectType , nowDBName , panelKey);
                        }else {
                            $.message.warning('提示：该浏览器无法获取父页面信息，为避免操作冲突，请关闭该子窗口，重新打开操作。');
                        }
                    } , 1000);
            		
            	}else{
            		if(data.failure){
            			win.getEl().unmask();
            			$.message.error(data.root);
            		}
            	}
            });
        }});
        var closeButton = new Ext.Button({text:'关闭',handler:function() {win.close()}});
        var buttons = submit ? ([appendButton , closeButton]) : ([closeButton]);
        var sqlArea = new Ext.ux.form.field.CodeMirror({readOnly:submit,value:content});
        var win = new IDB.Window({
            title:(submit ? '提交变更' : '查看SQL'),width:700,height:450,closable:true,layout:'fit',maximizable:true,
            items:[sqlArea],buttons:buttons
        });
    };
    var onlyExecuteSQL = function(content) {
        Ext.getBody().mask('正在提交并执行变更信息.....');
        ajax({
            url:'/structure/table/executeScript.do',
            params:{script:content , dbName:nowDBName},
            success:function(resp) {
                Ext.getBody().unmask();
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    $.feedbackMessage({
                        type: 'success',
                        message: '您好,恭喜已成功完成第一步，请到主菜单【sql审核提交】菜单项中进行审批操作！',
                        showTime:6000
                    });
                    setTimeout(function() {
                        window.parent.closeTabCallBack(tabId, nowDBName);
                    } , 350);
                }else {
                    $.feedbackMessage({
                        type: 'warning',
                        message: json.root
                    });
                }
            },
            failure:function(resp) {
                $.feedbackMessage({
                    type: 'danger',
                    message: resp.responseText ,
                    showTime:8000
                });
            }
        });
    };
    var panel = new Ext.Panel({
        region:'west',width:100,contentEl:'div_buttons'
    });
    var buttons = [
        {
            text:'保存',
            handler:function() {
                viewSQLOrSubmit(true);
            }
        }
    ];
    if(objectName && objectName != 'null') {
        buttons.push({
            text:'打开表数据',handler:function() {
                if(!objectName) {
                    $.message.warning('表尚未创建，不能用来查询。');
                }else if(window.parent) {
                    window.parent.queryObjectCallBack(nowDBName , objectName);
                }
            }
        },{
            text:'创建语句',
            handler:viewCreateSQL,
            hidden:true
        });
    }
    var cardPanel = TABLE_CARD_PANEL = new Ext.Panel({
        buttonAlign:'center',layout:'card',region:'center',bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',border:true,
        buttons:buttons,
        items:[
            //first show is column panel
            columnPanel = createColumnInfoPanel(),
            baseInfoPanel = createBaseInfoForm(),
            indexPanel = createIndexInfoPanel(columnPanel),
            referencePanel = createReferenceInfoPanel(columnPanel),
            partitionPanel = createPartitionPanel()
        ]
    });
    Ext.create('Ext.Viewport', {
        layout:'fit',
        items:[{
            layout:'border',
            items:[panel , cardPanel]
        }]
    });
    baseInfoPanel.setTitle('基本信息 (所在库：' + nowDBName + ")");
    if(objectName) {
        Ext.getBody().mask('正在加载表信息...');
        ajax({
            url:getRoot() + '/dataManage/table/getDBTableStructure',
            params:{tableName:objectName,dbName:nowDBName,baseType:now_db_type,dataBaseId:dataBase_id,dataSourceId:dataSource_id,dataSource:data_source,isLocal:isLocal},
            success:function(resp) {
                Ext.getBody().unmask();
                var json = jsonDecode(resp.responseText);
                json = json.responseText;
                if(json.success) {
                    var fields = baseInfoPanel.getForm().getFields();
                    var data = json.root;
                    baseInfoPanel.getForm().findField('engine').setValue(data['engine']);
                    baseInfoPanel.showHideByEngine();
                    fields.each(function(field) {
                        field.setValue(data[field.getName()]);
                    });

                    baseInfoPanel.initCollate(data['collate']);
                    columnPanel.setData(data.columns);
                    indexPanel.setData(data.indexes);
                    referencePanel.setData(data.references);
                    if(data.partitionContent) {
                        partitionPanel.setPartitionContent(data.partitionContent);
                    }else {
                        document.getElementById('partition').style.display = "none";
                    }
                }else {
                    $.message.error(json.root);
                }
            },
            failure:function() {
                Ext.getBody().unmask();
                $.message.warning('加载表信息失败。');
            }
        });
    }
    else {
        baseInfoPanel.getForm().findField('engine').setValue(db_default_engine);
        baseInfoPanel.showHideByEngine();
        baseInfoPanel.getForm().findField('charset').setValue(db_default_charset);
        baseInfoPanel.initCollate(db_default_collate);
    }
});
var createPartitionPanel = function() {
    var valueArea = new Ext.ux.form.field.CodeMirror({});
    return new Ext.Panel({
        layout:'fit',title:'分区描述',
        items:[
            valueArea
        ],
        setPartitionContent:function(content) {
            valueArea.setValue(content);
        },
        getPartitionContent:function() {
            return valueArea.getValue();
        }
    });
};
var createReferenceInfoPanel = function(columnPanel) {
    var dbListStore = new Ext.data.Store({
        fields:['data'],
        data:instanceDBS,
        proxy: {
            type: 'memory'
        }
    });
    var referenceOptionStore = new Ext.data.Store({
        fields:['data'],
        data:referenceOptionArray
    });
    var grid = new Ext.grid.Panel({
        selType:'rowmodel',
        region:'center',
        tbar:[
            {xtype:'tbspacer' , width:10},
            {
                text:'新增',iconCls:'addIcon',handler:function() {
                    appendGridRows(1 , grid);
                }
            },
            {xtype:'tbspacer' , width:10},
            {
                text:'删除',iconCls:'deleteIcon',handler:function() {
                    removeSelectedRows(grid);
                }
            }
        ],
        plugins:[
            new Ext.grid.plugin.CellEditing({
                clicksToEdit:1
            })
        ],
        columns:[
            {xtype: 'rownumberer'},
            { text: '外键名',  dataIndex: 'name' ,width:160 , editor:{xtype:'textfield',allowBlank:false}},
            { text: '包含列', dataIndex: 'columns',width:230,renderer:function(v) {
                if(v) {
                    return v + ' <a href="javascript:Ext.getCmp(\'' + grid.id + '\').editColumns()">编辑<a>';
                }
                return '<a href="javascript:Ext.getCmp(\'' + grid.id + '\').editColumns()">编辑</a>'
            }},
            {
                text: '参考库',  
                dataIndex: 'refDBName' ,
                width:140 , 
                editor:{
                xtype:'combo',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,
                store:dbListStore
            }},
            { text: '参考表',  dataIndex: 'refTableName' ,width:160 , editor:{xtype:'textfield'}},
            { text: '参考列', dataIndex: 'refColumns',width:230,renderer:function(v) {
                if(v) {
                    return v + ' <a href="javascript:Ext.getCmp(\'' + grid.id + '\').editRefColumns()">编辑<a>';
                }
                return '<a href="javascript:Ext.getCmp(\'' + grid.id + '\').editRefColumns()">编辑</a>';
            }},
            {text:'删除时',dataIndex:'deleteAction',width:200,editor:{
                allowBlank:true,
                xtype:'combo',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,
                store:referenceOptionStore
            }},
            {text:'修改时',dataIndex:'updateAction',width:200,editor:{
                allowBlank:true,
                xtype:'combo',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,
                store:referenceOptionStore
            }}
        ],
        store:new Ext.data.Store({
            fields:['name' , 'oldRefName' , 'columns' , 'refDBName'  , 'refTableName' , 'refColumns' , 'deleteAction' , 'updateAction'],
            data:{
                root:[]
            },
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    root: 'root'
                }
            }
        }),
        listeners:{
            afterrender:function(grid) {
                appendGridRows(1 , grid);
            }
        },
        editColumns:function() {
            var selectRow = grid.getSelectionModel().getSelection()[0];
            showColumnsPanelWindow(selectRow , columnPanel.getColumnNameDatas() , 'columns' , '请选择外键列');
        },
        editRefColumns:function() {
            var selectRow = grid.getSelectionModel().getSelection()[0];
            var refDBName = selectRow.get('refDBName') || nowDBName;
            var refTableName = selectRow.get('refTableName');
            if(!Ext.String.trim(refTableName)) {
                return $.message.warning('请先输入表名。');
            }
            var cacheArray = cacheRefColumns[refDBName + "&&&" + refTableName];
            if(cacheArray) {
                showColumnsPanelWindow(selectRow , cacheArray , 'refColumns' , '请选择参考列');
            }else {
            	var paramObj = {};
            	paramObj['dbName'] = refDBName;
            	paramObj['tableName'] = refTableName;
            	paramObj['baseType'] = now_db_type;
            	paramObj['dataBaseId'] = dataBase_id;
            	paramObj['dataSourceId'] = dataSource_id;
            	paramObj['dataSource'] = data_source;
            	paramObj['isLocal'] = isLocal;
            	var url = getRoot() + '/dataManage/showTableColumns';
            	$.post(url,paramObj,function(json){
            		if(json.success) {
                        cacheRefColumns[refDBName + "&&&" + refTableName] = json.root;
                        showColumnsPanelWindow(selectRow , json.root , 'refColumns' , '请选择参考列');
                    }else {
                        return $.message.error(json.root);
                    }
            	});
            }
        }
    });
    var cacheRefColumns = {};
    return new Ext.Panel({
        title:'编辑外键',layout:'border',
        items:[grid],
        setData:function(references) {
            var store = grid.store;
            store.removeAll();
            Ext.each(references , function(reference) {
                store.add(reference);
            });
        },
        getAllRows:function() {
            var references = [];
            grid.store.each(function(record) {
                references.push(record.data);
            });
            return references;
        }
    });
};
var mysqlIndexType = [
                      {"data" : "NORMAL", "label" : "NORMAL"},
                      {"data" : "UNIQUE", "label" : "UNIQUE"},
                      {"data" : "FULLTEXT", "label" : "FULL TEXT"}
                      ];
var mysqlIndexMethod = [
                        {"data" : "" , label : "--"},
                        {"data" : "BTREE" , "label" : "BTREE"},
                        {"data" : "HASH" , "label" : "HASH"}
                        ];
var oracleIndexType = [
                       {"data":"INDEX", "label":"INDEX"},
                       {"data":"UNIQUE", "label":"UNIQUE"},
                       {"data":"BITMAP", "label":"BITMAP"}
                       ];
var oracleIndexMethod = [
                         {"data" : "" , label : "--"},
                         {"data" : "ASC" , "label" : "ASC"},
                         {"data" : "DESC" , "label" : "DESC"}
                         ];
var createIndexInfoPanel = function(columnPanel) {
	var index_type,index_method;
	if(now_db_type == 'oracle'){
		index_type = oracleIndexType;
		index_method = oracleIndexMethod;
	}else{
		index_type = mysqlIndexType;
		index_method = mysqlIndexMethod;
	}
    var indexTypeStore = new Ext.data.Store({
        fields:['data' , 'label'],
        data:index_type
    });
    var indexMethodStore = new Ext.data.Store({
        fields:['data' , 'label'],
        data:index_method
    });
    var grid = new Ext.grid.Panel({
        title:'编辑索引',
        selType:'rowmodel',
        tbar:[
            {xtype:'tbspacer' , width:10},
            {
                text:'新增',iconCls:'addIcon',handler:function() {
                    appendGridRows(1 , grid);
                }
            },
            {xtype:'tbspacer' , width:10},
            {
                text:'删除',iconCls:'deleteIcon',handler:function() {
                    removeSelectedRows(grid);
                }
            }
        ],
        plugins:[
            new Ext.grid.plugin.CellEditing({
                clicksToEdit:1
            })
        ],
        columns:[
            {xtype: 'rownumberer'},
            { text: '索引名',  dataIndex: 'name' ,width:200 ,
                editor:{
                    xtype:'textfield',
                    allowBlank:false,
                    listeners:{
                        change:function(thiz) {
                            if(thiz.getValue() && grid.getSelectionModel().isSelected(grid.store.getCount() - 1)) {
                                appendGridRows(1 , grid);
                            }
                        }
                    }
                }
            },
            { text: '包含列', dataIndex: 'columns',width:330,renderer:function(v) {
                if(v) {
                    return v + ' <a href="javascript:Ext.getCmp(\'' + grid.id + '\').editIndexColumn()">编辑<a>';
                }
                return '<a href="javascript:Ext.getCmp(\'' + grid.id + '\').editIndexColumn()">编辑</a>'
            }},
            { text: '索引类型', dataIndex: 'type',width:140 , editor:{
                xtype:'combo',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,store:indexTypeStore,allowBlank:false,
                listeners:{
                    select:function(thiz) {
                        if(thiz.getValue() == 'FULLTEXT') {
                            grid.getSelectionModel().getSelection()[0].set('method' , '');
                        }
                    }
                }
            }},
            {
                text: '索引方式', dataIndex: 'method',width:140,editor:{xtype:'combo',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,store:indexMethodStore,allowBlank:false
            }}
        ],
        store:new Ext.data.Store({
            fields:['name' , 'oldIndexName', 'type' , 'method' , 'columns'],
            data:{
                root:[]
            },
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    root: 'root'
                }
            }
        }),
        listeners:{
            afterrender:function(grid) {
                appendGridRows(1 , grid);
                grid.getSelectionModel().select(grid.store.getCount() - 1);
            },
            beforeEdit:function(grid,e) {
                if(e.record.get('type') == 'FULLTEXT' && e.column.dataIndex == 'method') {
                    return false;
                }
                return true;
            }
        },
        editIndexColumn:function() {
            var selectRow = grid.getSelectionModel().getSelection()[0];
            showIndexColumnsPanelWindow(selectRow , columnPanel.getColumnNameDatas());
        },
        getAllRows:function() {
            var indexes = [];
            grid.store.each(function(record) {
                if(record.get('name')) {
                    indexes.push(record.data);
                }
            });
            return indexes;
        },
        setData:function(indexes) {
            var store = grid.store;
            store.removeAll();
            Ext.each(indexes , function(index) {
                store.add(index);
            });
            appendGridRows(1 , grid);
            grid.getSelectionModel().select(grid.store.getCount() - 1);
        }
    });
    return grid;
};
var showColumnsPanelWindow = function(record , columnsArray , name ,title) {
    var existsValues = record.get(name);
    var existsValueArray = getIndexColumnArrayByDefine(existsValues , columnsArray);
    existsValueArray.push({});
    var selectStore = new Ext.data.Store({
        fields:['data'],
        data:columnsArray,
        proxy: {
            type: 'memory'
        }
    });
    var cellEditing = new Ext.grid.plugin.CellEditing({
        clicksToEdit:1
    });
    var grid = new Ext.grid.Panel({
        selType:'rowmodel',
        viewConfig:{ stripeRows:true, enableTextSelection:true},
        plugins:[
            cellEditing
        ],
        columns:[
            {xtype: 'rownumberer'},
            {text: '列信息',  dataIndex: 'data' ,sortable:false ,flex:1, editor:{
                xtype:'combo',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,store:selectStore,allowBlank:false
            }}
        ],
        store:new Ext.data.Store({
            fields:['data'],
            data:existsValueArray,
            proxy: {
                type: 'memory'
            }
        })
    });
    var win = new IDB.Window({
        height:460 , width:400 , title : title,items:[grid]
        ,
        buttonAlign:'center',
        buttons:[
        {
            text:'+',width:40,handler:function() {
            appendGridRows(1 , grid);
        }
        },
        {
            text:'-',width:40,handler:function() {
            removeSelectedRows(grid);
        }
        },
        {
            text:'保存',handler:function() {
            cellEditing.completeEdit();
            var v = '' , columnsSet = {};
            grid.store.each(function(row) {
                var value = row.get('data');
                if(value && !columnsSet[value]) {
                    columnsSet[value] = '1';
                    v += row.get('data') + ',';
                }
            });
            if(v) {
                v = v.substring(0 , v.length - 1);
            }
            record.set(name , v);
            win.close();
        }
        },
        {
            text:'取消',handler:function() {win.close();}
        }
        ]
    });
};
var showIndexColumnsPanelWindow = function(record , columnsArray) {
    var existsValues = record.get('columns');
    var existsValueArray = getIndexColumnArrayByDefine(existsValues , columnsArray);
    existsValueArray.push({});
    var selectStore = new Ext.data.Store({
        fields:['data'],
        data:columnsArray,
        proxy: {
            type: 'memory'
        }
    });
    var cellEditing = new Ext.grid.plugin.CellEditing({
        clicksToEdit:1
    });
    var grid = new Ext.grid.Panel({
        selType:'rowmodel',
        plugins:[
            cellEditing
        ],
        columns:[
            {xtype: 'rownumberer'},
            {text: '列信息',  dataIndex: 'data' ,sortable:false ,flex:1, editor:{
                xtype:'combo',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,store:selectStore,allowBlank:false,
                listeners:{
                    change:function(thiz) {
                        if(thiz.getValue() && grid.getSelectionModel().isSelected(grid.store.getCount() - 1)) {
                            appendGridRows(1 , grid);
                        }
                    }
                }
            }},
            {text: '前缀长度' , dataIndex:'length' , sortable:false , width:120 ,editor:{
                xtype:'numberfield',allowDecimals:false,
                minValue:0,
                negativeText:'不允许输入负数',
                nanText:'无效数字字符'
            }}
        ],
        store:new Ext.data.Store({
            fields:['data','length'],
            data:existsValueArray,
            proxy: {
                type: 'memory'
            }
        }),
        listeners:{
            afterrender:function() {
                //appendGridRows(1 , grid);
                grid.getSelectionModel().select(grid.store.getCount() - 1);
            }
        }
    });
    var win = new IDB.Window({
        height:460 , width:400 , title : '请选择索引列及前缀长度',items:[grid],
        buttonAlign:'center',
        buttons:[
            {
                text:'+',width:40,handler:function() {
                appendGridRows(1 , grid);
            }
            },
            {
                text:'-',width:40,handler:function() {
                removeSelectedRows(grid);
            }
            },
            {
                text:'保存',handler:function() {
                cellEditing.completeEdit();
                var v = '' , columnsSet = {};
                grid.store.each(function(row) {
                    var value = row.get('data');
                    var length = row.get('length');
                    if(value && !columnsSet[value]) {
                        columnsSet[value] = '1';
                        v += row.get('data');
                        if(length) {
                            v += '(' + length + ')';
                        }
                        v += ',';
                    }
                });
                if(v) {
                    v = v.substring(0 , v.length - 1);
                }
                record.set('columns' , v);
                win.close();
            }
            },
            {
                text:'取消',handler:function() {win.close();}
            }
        ]
    });
};
var convertColumnArrayToMap = function(columnArray) {
    var map = {};
    Ext.each(columnArray , function(row) {
        map[row['data']] = "1";
    });
    return map;
};
var getIndexColumnArrayByDefine = function(v,columnArray) {
    if(!v) return [];
    var map = convertColumnArrayToMap(columnArray);
    var array = v.split(',');
    var valueArray = [];
    Ext.each(array , function(row) {
        var begin = row.indexOf("(") , end = row.indexOf(")");
        if(begin != - 1 && end != -1)  {
            var columnName = Ext.String.trim(row.substring(0 , begin));
            if(map[columnName]) {
                var length = row.substring(begin + 1 , end);
                valueArray.push({data:columnName , length : length});
            }
        }else {
            if(map[row]) {
                valueArray.push({data:row});
            }
        }
    });
    return valueArray;
};
var isNumberType = function(type) {
   return type == 'boolean' || type == 'bool' || type == 'tinyint' || type == 'smallint' ||
           type == 'mediumint' || type == 'int' || type == 'integer' || type == 'bigint';
};
var isFloatNumberType = function(type) {
    return type == 'real' || type == 'double' || type == 'float' || type == 'numeric' || type == 'decimal';
};
var isCharType = function(type) {
    return type == 'char' || type == 'varchar';
};
var isTextType = function(type) {
    return type == 'tinytext' || type == 'text' || type == 'mediumtext' || type == 'longtext';
};
var isSetType = function(type) {return type == 'set'};
var isEnumType = function(type) {return type == 'enum'};
var isTimestamp = function(type) {return type == 'timestamp'};
var isDatetime = function(type) {return type == 'datetime'};
var isOnDefaultTimestamp = function(type) {
    return isTimestamp(type) || (isMoreOrEqual5_6Version && isDatetime(type));
};
var isNoDefaultFieldType = function(type) {
    return type == 'tinyblob' || type == 'blob' || type == 'mediumblob' || type == 'longblob'
         || type == 'linestring' || type == 'polygon' || type == 'geometry' || type == 'multipoint'
         || type == 'multilinestring' || type == 'multipolygon' || type == 'geometrycollection';
};

var isOracleCharType = function(type) {
	return type == 'char' || type == 'varchar2' ||type == 'clob';
};
var isOracleNumberType = function(type) {
	return type == 'number';
};
var isOracleBinaryType = function(type) {
	return type == 'blob' || type == 'raw';
};
var isOracleDateType = function(type) {
	return type == 'date';
};
var isOracleDatePrecisionType = function(type){
	return type == 'timestamp';
};
var isOracleDateSecondPrecisionType = function(type){
	return type == 'interval day to second';
};
var isOracleDateYearPrecisionType = function(type){
	return type == 'interval year to month';
};

var appendGridRows = function(rows,grid,appendRow) {
    for(var i = 0 ; i < rows ; i++) {
        grid.store.add(appendRow || {});
    }
};
var insertGridRows = function(grid,appendRow) {
    var selectedRows = grid.getSelectionModel().getSelection();
    if(!selectedRows || selectedRows.length == 0) {
        $.message.warning('请先选择要插入的位置。');
    }else {
        var index = grid.store.indexOf(selectedRows[0]);
        grid.store.insert(index , appendRow || {});
        grid.getView().refresh();
    }
};
var removeSelectedRows = function(grid) {
    var selectedRows = grid.getSelectionModel().getSelection();
    if(!selectedRows || selectedRows.length == 0) {
        return $.message.warning('请先选择要删除的行。');
    }
    Ext.each(selectedRows , function(row) {
        grid.store.remove(row);
    });
    grid.getView().refresh();
};
var charsetCollateArray = {};
var createColumnInfoPanel = function() {
	var dbcolumnTypeArray;
	if(now_db_type == 'oracle'){
		dbcolumnTypeArray = oracleColumnTypeArray;
	}else{
		dbcolumnTypeArray = columnTypeArray;
	}
    var columnTypeStore = new Ext.data.Store({
        fields:['data' , 'label'],
        data:dbcolumnTypeArray
    });
    var selectRowCallBack = function(grid,record) {
        if(tmpRecord != null) {
            if(tmpRecord == record) return;
            copyFormToRecord();
        }
        tmpRecord = record;
        formPanel.loadRecord(record);
        typeControl(record.get('columnType') , record);
    };
    var rightMenu = new Ext.menu.Menu({
        items:[{
            text:'新增',handler:function() {appendRows(1)}
        },{
            text:'插入',handler:function() {insertGridRows(columnPanel , {nullable:true});}
        },{
            text:'删除',handler:function() {removeSelectedRows(columnPanel);}
        },{
            text:'上移',handler:function() {upRow();}
        },{
            text:'下移',handler:function() {downRow();}
        }]
    });
    var columnPanel = new Ext.grid.Panel({
        region:'center',
        selType:'rowmodel',
        plugins:[
            new Ext.grid.plugin.CellEditing({
                clicksToEdit:1
            })
        ],
        columns:[
            {xtype: 'rownumberer'},
            {text: '列名',  dataIndex: 'columnName' ,width:260,sortable:false ,
                editor:{
                    xtype:'textfield',
                    allowBlank:false,
                    listeners:{
                        change:function(thiz) {
                            if(thiz.getValue() && columnPanel.getSelectionModel().isSelected(columnPanel.store.getCount() - 1)) {
                                appendRows(1);
                            }
                        }
                    }
                }
            },
            {text: '类型', dataIndex: 'columnType',width:180 ,sortable:false,
                editor:{
                    xtype:'combo',
                    triggerAction:'all',
                    displayField:'label',
                    valueField:'data',
                    queryMode:'local',
                    forceSelection:true,
                    typeAhead:true,store:columnTypeStore,allowBlank:false,
                    listeners:{
                        select:function(thiz) {
                            typeControl(thiz.getValue() , tmpRecord);
                        }
                    }
                }
            },
            {
                text: '长度', dataIndex: 'length',width:120,sortable:false,editor:{
                    xtype:'numberfield',allowDecimals:false,
                    minValue:0,
                    negativeText:'不允许输入负数',
                    nanText:'无效数字字符'
                }
            },
            {text:'备注',dataIndex:'comments',width:140,sortable:false,editor:{xtype:'textarea'}},
            { text: '可空' , dataIndex: 'nullable',width:100 ,sortable:false, xtype:'checkcolumn',listeners:{
                  checkchange:function(thiz,rowIndex,checked) {
                      var row = columnPanel.getStore().getAt(rowIndex);
                      if(checked && row.get('primaryKey')) {
                          row.set('nullable' , "");
                      }
                      columnPanel.getSelectionModel().select(rowIndex);
                      selectRowCallBack(columnPanel , row);
                  }
            }},
            { text: '主键' , dataIndex: 'primaryKey',width:100 ,sortable:false, xtype:'checkcolumn',listeners:{
                    checkchange:function(thiz,rowIndex,checked) {
                        var row = columnPanel.getStore().getAt(rowIndex);
                        if(checked) {
                            row.set('nullable' , "");
                        }
                        columnPanel.getSelectionModel().select(rowIndex);
                        selectRowCallBack(columnPanel , row);
                    }
                }
            }
        ],
        store:new Ext.data.Store({
            fields:['id','columnName' , 'oldColumnName' , 'columnType' , 'length' , 'scale' ,'nullable' , 'primaryKey',
                     'defaults','comments' ,//扩展信息
                     'autoIncrement' , 'unsigned' , 'zerofill',//数字专用
                    'charset','collate','binary',//字符专用
                    'values','defaultsEnumValue','defaultSetValue','onUpdateTimestamp'//用于set、enum数据类型
            ],
            data:{
                root:[]
            },
            proxy: {
                type: 'memory',
                reader: {
                    type: 'json',
                    root: 'root'
                }
            }
        }),
        tbar:[
            {xtype:'tbspacer' , width:10},
            {
                text:'新增',iconCls:'addIcon',handler:function() {
                    appendRows(1);
                }
            },
            {xtype:'tbspacer' , width:10},
            {
                text:'插入',iconCls:'addIcon2',handler:function() {
                    insertGridRows(columnPanel , {nullable:true});
                }
            },
            {xtype:'tbspacer' , width:10},
            {
                text:'删除行',iconCls:'deleteIcon',handler:function() {
                    removeSelectedRows(columnPanel);
                }
            },
            {xtype:'tbspacer' , width:10},
            {
                text:'上移',iconCls:'upIcon',handler:function() {upRow();}
            },
            {xtype:'tbspacer' , width:10},
            {
                text:'下移',iconCls:'downIcon',handler:function() {downRow();}
            }
        ],
        listeners:{
            itemclick:selectRowCallBack,
            afterrender:function() {
                appendRows(1);
                columnPanel.getSelectionModel().select(columnPanel.store.getCount() - 1);
            },
            itemcontextmenu:function(thiz, record, item, index, e) {
                e.preventDefault();
                rightMenu.showAt(e.getXY());
                selectRowCallBack(thiz,record);
            }
        }
    });
    var upRow = function() {
        var store = columnPanel.store;
        var selectedRows = columnPanel.getSelectionModel().getSelection();
        if(!selectedRows || selectedRows.length == 0) {
            $.message.warning('请先选择要移动的行。');
        }else {
            var first = selectedRows[0];
            if(first == store.first()) {
                $.message.warning('已经是第一行。');
            }else {
                var rowIndex = store.indexOf(first);
                store.removeAt(rowIndex);
                store.insert(rowIndex - 1 , first);
                columnPanel.getSelectionModel().select(first);
                columnPanel.getView().refresh();
            }
        }
    };
    var downRow = function() {
        var store = columnPanel.store;
        var selectedRows = columnPanel.getSelectionModel().getSelection();
        if(!selectedRows || selectedRows.length == 0) {
            $.message.warning('请先选择要移动的行。');
        }else {
            var first = selectedRows[0];
            if(first == store.last()) {
                $.message.warning('已经是最后一行。');
            }else {
                var rowIndex = store.indexOf(first);
                store.removeAt(rowIndex);
                store.insert(rowIndex + 1 , first);
                columnPanel.getSelectionModel().select(first);
                columnPanel.getView().refresh();
            }
        }
    };
    var tmpRecord = null;
    var appendRows = function(rows) {
        rows = rows || 1;
        appendGridRows(rows , columnPanel , {nullable:false});
    };

    var copyFormToRecord = function() {
        if(!tmpRecord) return;
        var fields = formPanel.getForm().getFields();
        fields.each(function(field) {
            if(!field.hidden) {
                tmpRecord.set(field.getName() , field.getValue());
            }else {
                tmpRecord.set(field.getName() , null);
            }
        });
    };

    var typeControl = function(type , record) {
        var checkboxGroup = Ext.getCmp('number_checkbox_group');
        var valuesCheckPanel = Ext.getCmp('values_check_panel');
        var setValuePanel = Ext.getCmp('set_value_panel');

        var allFields = formPanel.getForm().getFields();
        checkboxGroup.hide();
        valuesCheckPanel.hide();
        setValuePanel.hide();
        isEnumValue = false;
        allFields.each(function(field) {
            var name = field.getName();
            if(name && !field.hidden) {
                field.hide();
            }
        });
        columnDefaultsStore.remove({data:'CURRENT_TIMESTAMP',label:'CURRENT_TIMESTAMP'});
        var showCharset = true , defaultTimestamp = false;
        if(isNumberType(type) || isOracleNumberType(type)) {
            checkboxGroup.show();
            showArray(['defaults' , 'unsigned' , 'zerofill' , 'autoIncrement']);
            showCharset = false;
        }else if(isFloatNumberType(type)) {
            checkboxGroup.show();
            showArray(['defaults' , 'unsigned' , 'zerofill' , 'scale']);
            showCharset = false;
        }else if(isCharType(type) || isOracleCharType(type)) {
            /*showArray(['defaults' , 'charset' , 'collate' , 'binary']);*/
        	showArray(['defaults']);
        	showCharset = false;
        }else if(isOnDefaultTimestamp(type) || isOracleDateType(type) || isOracleDatePrecisionType(type) || isOracleDateSecondPrecisionType(type) || isOracleDateSecondPrecisionType(type) ) {
            showArray(['defaults' , 'onUpdateTimestamp']);
            columnDefaultsStore.add({data:'CURRENT_TIMESTAMP',label:'CURRENT_TIMESTAMP'});
            defaultTimestamp = true;
        }else if(isTextType(type)) {
            showArray(['charset' , 'collate']);
        }else if(isSetType(type)) {
            valuesCheckPanel.show();
            setValuePanel.show();
            showArray(['values' , 'defaultSetValue' , 'charset' , 'collate']);
        }else if(isEnumType(type)){
            isEnumValue = true;
            valuesCheckPanel.show();
            fillEnumValuesToSelect(record.get('defaultsEnumValue'));
            showArray(['values' , 'defaultsEnumValue' , 'charset' , 'collate']);
        }else if(!isNoDefaultFieldType(type)) {
            showArray(['defaults']);
            showCharset = false;
        }
        
        if(showCharset) {
            processCharsetCollate(record.get('charset') , record.get('collate'));
        }
        if(!defaultTimestamp) {
            var index = columnDefaultsStore.find('data' , 'CURRENT_TIMESTAMP');
            if(index >= 0) {
                columnDefaultsStore.removeAt(index);
            }
        }
        if(type == 'varchar' && !record.get('length')) {
            record.set('length' , '32');
        }else if(type == 'int' && !record.get('length')) {
            record.set('length' , '11');
        }
    };
    var processCharsetCollate = function(charset , collate) {
        if(charset) {
            if(charsetCollateArray[charset]) {
                collateField.store.loadData(charsetCollateArray[charset]);
                if(collate) {
                    collateField.setValue(collate);
                }
                charsetField.setValue(charset);
            }else {
                collateField.store.load({
                    params:{charset:charset,dbtype:now_db_type},
                    callback:function(records) {
                        if(collate) {
                            collateField.setValue(collate);
                        }
                        var arrayData = [];
                        Ext.each(records , function(rec) {
                            arrayData.push(rec.data);
                        });
                        charsetField.setValue(charset);
                        charsetCollateArray[charset] = arrayData;
                    }
                });
            }
        }
    };
    var isEnumValue = false;

    var fillEnumValuesToSelect = function(v) {
        var values = formPanel.getForm().findField('values');
        var selectData = getEnumDataArrayByValue(values.getValue());
        var defaultsEnumValueField = formPanel.getForm().findField('defaultsEnumValue');
        defaultsEnumValueField.store.loadData(selectData);
        if(v) {
            defaultsEnumValueField.setValue(v);
        }
    };

    var showArray = function(array)  {
        var form = formPanel.getForm();
        Ext.each(array , function(row) {
            var field = form.findField(row);
            field.show();
        });
    };
    var columnDefaultsStore = new Ext.data.Store({
        fields:['data' , 'label'],
        data:[{data:'',label:''},{data:'$empty_string$',label:'Empty String'}]
    });
    var formPanel = new IDB.FormPanel({
        height:164,title:'扩展信息',region:'south',//collapsible:true,
        defaults:{width:600,allowBlank:true},
        items:[
            {
                xtype:'panel',
                border:false,
                hidden:true,
                id:'values_check_panel',
                padding:'3 0 3 0',
                width:605,
                layout:{
                    type:'hbox'
                },
                items:[{
                    fieldLabel:'值列表',
                    xtype:'textfield',
                    name:'values',
                    labelWidth:80,
                    labelAlign:'right',
                    flex:1,
                    readOnly:true
                },{
                    xtype:'button',
                    text:'...',
                    handler:function() {
                        var field = formPanel.getForm().findField('values');
                        if(isEnumValue) {
                            showValuesPanelWindow(field , fillEnumValuesToSelect);
                        }else {
                            showValuesPanelWindow(field);
                        }
                    }
                }]
            },
            {
                padding:'3 0 3 0',
                fieldLabel:'小数点',
                name:'scale',
                hidden:true,
                xtype:'numberfield',
                allowDecimals:false,
                minValue:0,
                negativeText:'不允许输入负数',
                nanText:'无效数字字符'
            },
            {
                xtype:'panel',
                border:false,
                hidden:true,
                padding:'3 0 3 0',
                id:'set_value_panel',
                width:605,
                layout:{
                    type:'hbox'//,align: 'stretch'
                },
                items:[{
                    fieldLabel:'默认值',
                    xtype:'textfield',
                    name:'defaultSetValue',
                    labelWidth:80,
                    labelAlign:'right',
                    flex:1,
                    readOnly:true
                },{
                    xtype:'button',
                    text:'...',handler:function() {
                        var valueField = formPanel.getForm().findField('values');
                        var defaultSetValueField = formPanel.getForm().findField('defaultSetValue');
                        showSetValueFieldWindow(valueField , defaultSetValueField);
                    }
                }]
            },
            {
                fieldLabel:'默认值',
                xtype:'combo',
                name:'defaultsEnumValue',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                hidden:true,
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data'],
                    data:[]
                })
            },
            {
                padding:'3 0 3 0',
                fieldLabel:'默认值',
                name:'defaults',
                xtype:'combo',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                hidden:true,
                forceSelection:false,
                typeAhead:true,
                store:columnDefaultsStore
            },{
                xtype:'checkboxfield',
                name:'onUpdateTimestamp',
                margin:"0 0 0 26",
                boxLabel:'根据当前时间更新',
                hidden:true
            },
            {
                xtype:'checkboxfield',
                name:'autoIncrement',
                fieldLabel:'自动增长',
                hidden:true
            },
            {
                xtype:'checkboxgroup',
                fieldLabel:'数字选项',
                id:'number_checkbox_group',
                columns:4,
                hidden:true,
                items:[
                    {boxLabel:'无符号',name:'unsigned'},
                    {boxLabel:'ZEROFILL',name:'zerofill'}
                ]
            },
            {
                fieldLabel:'字符集',
                xtype:'combo',
                name:'charset',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                hidden:true,
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data' , 'label'],
                    data:charSetDataArray
                })
            },
            new IDB.CommonBox({
                fieldLabel:'校验规则',
                store:new IDB.CommonBoxStore({
                    url:getRoot()+'/dataManage/findCollateByCharset',
                    autoLoad:false
                }),
                name:'collate',
                labelAlign:'right',
                editable:false,
                labelWidth:80,
                width:580,
                hidden:true
            }),
            {
                xtype:'checkboxfield',
                name:'binary',
                fieldLabel:'二进制',
                hidden:true,
                width:580
            }
        ]
    });

    var charsetField = formPanel.getForm().findField('charset');
    var collateField = formPanel.getForm().findField('collate');

    charsetField.on('select' , function() {
        processCharsetCollate(charsetField.getValue());
    });
    return new Ext.Panel({
        title:'编辑列 (所在库：' + nowDBName + ")",layout:'border',
        //border:true,
        //bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',
        getColumnNameDatas:function() {
            var columnArray = [] , arraySet = {};
            columnPanel.store.each(function(record) {
                var columnName = record.get('columnName');
                columnName = Ext.String.trim(columnName);
                if(columnName && !arraySet[columnName]) {
                    arraySet[columnName] = "1";
                    columnArray.push({data:columnName});
                }
            });
            return columnArray;
        },
        getAllRows:function() {
            copyFormToRecord();
            var successRows = [];
            var autoIncrementCount = 0;
            columnPanel.store.each(function(record) {
                var columnName = record.get('columnName');
                var columnType = record.get('columnType');
                if(record.get('autoIncrement')) {
                    autoIncrementCount++;
                }
                if(Ext.String.trim(columnName) || Ext.String.trim(columnType)) {
                    if(!isOnDefaultTimestamp(columnType)) {
                        record.set("onUpdateTimestamp" , "");
                    }
                    if(isFloatNumberType(columnType)) {//浮点类型，输入了长度但未设置精度补充0
                        var length = record.get('length');
                        var scale = record.get('scale');
                        if(length && !scale && scale !== 0) {
                            record.set('scale' , '0');
                        }
                    }
                    successRows.push(record.data);
                }
            });
            if(successRows.length == 0) {
                $.message.warning('没有任何属性，无法生成创建表语句...');return false;
            }
            if(autoIncrementCount > 1) {
                $.message.warning('一个表只能有一个AUTO_INCREMENT字段...');return false;
            }
            return successRows;
        },
        items:[
            columnPanel , formPanel
        ],
        setData:function(columns) {
            var store = columnPanel.store;
            store.removeAll();
            Ext.each(columns , function(row) {
                store.add(row);
            });
            appendRows(1);
            columnPanel.getSelectionModel().select(store.getCount() - 1);
        }
    });
};
var getEnumDataArrayByValue = function(v) {
    if(!v) return [];
    var array = v.split(',');//值当中不允许存在逗号
    var valueArray = [];
    Ext.each(array , function(row) {
        row = row.replaceAll("''" , "'");
        if(row.charAt(0) == '\'') {
            valueArray.push({data:row.substring(1 , row.length - 1)});
        }else {
            valueArray.push({data:row});
        }
    });
    return valueArray;
};
var showSetValueFieldWindow = function(valueField , defaultSetValueField) {
    var existsValues = valueField.getValue();
    var defaultValue = defaultSetValueField.getValue();

    var defaultValueMap = {};
    if(defaultValueMap) {
        var tmpArray = defaultValue.split(",");
        Ext.each(tmpArray , function(row) {
            row = row.replaceAll("''" , "'");
            if(row.charAt(0) == '\'') {
                row = row.substring(1 , row.length - 1)
            }
            defaultValueMap[row] = "1";
        });
    }
    var existsValueArray = getEnumDataArrayByValue(existsValues);
    var cellEditing = new Ext.grid.plugin.CellEditing({
        clicksToEdit:1
    });
    var grid = new Ext.grid.Panel({
        selType:'checkboxmodel',
        multiSelect:true,
        plugins:[
            cellEditing
        ],
        columns:[
            {text: '值列表',  dataIndex: 'data' ,sortable:false ,flex:1, editor:{xtype:'textfield',allowBlank:false}}
        ],
        store:new Ext.data.Store({
            fields:['data'],
            data:existsValueArray,
            proxy: {
                type: 'memory'
            }
        }),
        listeners:{
            afterrender:function() {
                var preSelectRecords = [];
                grid.store.each(function(record) {
                    if(defaultValueMap[record.get('data')]) {
                        preSelectRecords.push(record);
                    }
                });
                if(preSelectRecords.length > 0) {
                    grid.getSelectionModel().select(preSelectRecords);
                }
            }
        }
    });

    var win = new IDB.Window({
        height:400 , width:400 , title : '设置默认值，请选择值列表或默认NULL',items:[grid],
        buttonAlign:'center',
        buttons:[
            {
                text:'保存',handler:function() {
                cellEditing.completeEdit();
                var selectedRows = grid.getSelectionModel().getSelection();
                var result = '';
                Ext.each(selectedRows , function(record) {
                    var v = record.get('data');
                    if(v) {
                        result += v + ',';
                    }
                });
                if(result.length > 0) {
                    result = result.substring(0 , result.length - 1);
                }
                defaultSetValueField.setValue(result);
                win.close();
            }
            },
            {
                text:'NULL',handler:function() {defaultSetValueField.setValue('NULL');}
            },
            {
                text:'取消',handler:function() {win.close();}
            }
        ]
    });
};
var showValuesPanelWindow = function(field , callBackFun) {
    var existsValues = field.getValue();
    var existsValueArray = getEnumDataArrayByValue(existsValues);
    existsValueArray.push({});
    var cellEditing = new Ext.grid.plugin.CellEditing({
        clicksToEdit:1
    });
    var grid = new Ext.grid.Panel({
        selType:'rowmodel',
        plugins:[
            cellEditing
        ],
        columns:[
            {xtype: 'rownumberer'},
            {text: '值列表',  dataIndex: 'data' ,sortable:false ,flex:1, editor:{xtype:'textfield',allowBlank:false}}
        ],
        store:new Ext.data.Store({
            fields:['data'],
            data:existsValueArray,
            proxy: {
                type: 'memory'
            }
        })
    });
    var win = new IDB.Window({
        height:400 , width:400 , title : '请输入值列表',items:[grid],
        buttons:[
            {
                text:'+',width:40,handler:function() {
                cellEditing.completeEdit();
                appendGridRows(1 , grid);
            }
            },
            {
                text:'-',width:40,handler:function() {
                cellEditing.completeEdit();
                removeSelectedRows(grid);
            }
            },
            {
                text:'保存',handler:function() {
                cellEditing.completeEdit();
                var result = '' , error = false , setValue = {};
                grid.store.each(function(row) {
                    var v = row.get('data');
                    if(!error && v) {
                        if(v.indexOf(',') != -1) {
                            $.message.warning('数据:' + v + "包含逗号。");
                            error = true;
                        }
                        if(!setValue[v]) {
                            setValue[v] = "1";
                            if(v.indexOf('\'') != -1) {
                                v = v.replaceAll("'","''");
                            }
                            result += '\'' + v + '\',';
                        }
                    }
                });
                if(result.length > 0) {
                    result = result.substring(0 , result.length - 1);
                }
                field.setValue(result);
                if(callBackFun) {
                    callBackFun.call(this);
                }
                win.close();
            }
            },
            {
                text:'取消',handler:function() {cellEditing.completeEdit();win.close();}
            }
        ]
    });
};

var createBaseInfoForm = function() {
	var flag = true;
	if (now_db_type == 'mysql' || now_db_type == 'drds') {
		flag = true;
	}
	if(now_db_type == 'oracle'){
		flag = false;
	}
	var projectStore = new Ext.data.Store({
		fields:['data','label'],
		data : projectListArray
	});
    var form = new IDB.FormPanel({
        title:'基本信息' , height:110,
        defaults:{
            bodyPadding:5,
            padding:'0 5 0 5',
            xtype:'fieldset',
            width:600,
            defaults:{
                autoFitErrors:false,//自动调整错误提示时候的宽度
                labelSeparator:' : ',
                labelWidth:80,
                width:550,
                labelAlign:'right',
                xtype:'textfield'
            }
        },
        items:[
            {
                title:'基本信息',
                items:[
                    {
                        padding:'5 0 0 0',
                        fieldLabel:'<span style="color: red">*</span> 表名',
                        allowBlank:false,
                        name:'tableName',
                        blankText:'表名不能为空'
                    },
                    {
                        xtype:'textarea',
                        fieldLabel:'备注',
                        name:'comment',
                        height:40,
                        //hidden:true,
                        allowBlank:true
                    },
                    {
                    	padding:'5 0 0 0',
                    	fieldLabel:'<span style="color:red">*</span> 部门负责人邮箱',
                    	allowBlank:false,
                    	name:'auserEmail',
                    	blankText:'部门负责人地址不能为空'
                    },
                    {
                    	fieldLabel:'项目组',
                    	xtype:'combo',
                    	triggerAction:'all',
                    	displayField:'label',
                    	valueField:'data',
                    	queryMode:'local',
                    	name:'projectName',
                    	forceSelection:true,
                    	typeAhead:true,
                    	editable:false,
                    	store:projectStore
                    },
                    {
                    	fieldLabel:'SQL类别',
                    	xtype:'combo',
                    	triggerAction:'all',
                    	displayField:'label',
                    	valueField:'data',
                    	queryMode:'local',
                    	name:'sqlType',
                    	forceSelection:true,
                    	typeAhead:true,
                    	editable:false,
                    	store:new Ext.data.Store({
                    		fields:['data','label'],
                    		data:[{'data':'A SQL','label':'A SQL'},{'data':'B SQL','label':'B SQL'}]
                    	})
                    },
                    {
                    	padding:'5 0 0 0',
                    	fieldLabel:'<span style="color:red">*</span> SQL用途',
                    	allowBlank:false,
                    	name:'sqlUsage',
                    	blankText:'SQL用途说明不能为空.'
                    },
                    {
                        fieldLabel:'存储引擎',
                        xtype:'combo',
                        triggerAction:'all',
                        displayField:'label',
                        valueField:'data',
                        queryMode:'local',
                        name:'engine',
                        forceSelection:true,
                        typeAhead:true,
                        editable:flag,
                        store:new Ext.data.Store({
                            fields:['data' , 'label'],
                            data:engineDataArray
                        })
                    },
                    {
                        fieldLabel:'字符集',
                        xtype:'combo',
                        name:'charset',
                        triggerAction:'all',
                        displayField:'label',
                        valueField:'data',
                        queryMode:'local',
                        forceSelection:true,
                        typeAhead:true,
                        editable:flag,
                        store:new Ext.data.Store({
                            fields:['data' , 'label'],
                            data:charSetDataArray
                        })

                    },
                    new IDB.CommonBox({
                        fieldLabel:'校验规则',
                        store:new IDB.CommonBoxStore({
                            url:getRoot()+'/dataManage/findCollateByCharset',
                            autoLoad:false
                        }),
                        name:'collate',
                        labelAlign:'right',
                        editable:false,
                        labelWidth:80//,
                        //width:530
                    })
                ]
            },
            {
                title:'更多选项',
                collapsible:true,
                collapsed:true,
                items:[
                    {
                        fieldLabel:'自增当前值',
                        xtype:'numberfield',
                        name:'autoIncrement',
                        minValue:1,
                        allowDecimals:false,
                        nanText:'无效数字字符',
                        negativeText:'不允许输入负数'
                    },
                    {
                        fieldLabel:'行格式',
                        xtype:'combo',
                        name:'rowFormat',
                        triggerAction:'all',
                        displayField:'label',
                        valueField:'data',
                        queryMode:'local',
                        forceSelection:true,
                        editable:false,
                        typeAhead:true,
                        store:new Ext.data.Store({
                            fields:['data' , 'label'],
                            data:rowFormatDataArray
                        }),
                        /*tpl: Ext.create('Ext.XTemplate',
                            '<tpl for=".">',
                            '<div class="x-boundlist-item">{label}</div>',
                            '</tpl>'
                        ),*/
                        // template for the content inside text field
                        displayTpl: Ext.create('Ext.XTemplate',
                            '<tpl for=".">',
                            '{data}',
                            '</tpl>'
                        )
                    },
                    {
                        fieldLabel:'平均行长度',
                        xtype:'numberfield',
                        name:'avgRowLength',
                        allowDecimals:false,
                        minValue:0,
                        negativeText:'不允许输入负数',
                        nanText:'无效数字字符'
                    },
                    {
                        id:'minRows',
                        xtype:'numberfield',
                        fieldLabel:'最小行',
                        name:'minRows',
                        blankText:'该项不能为空...'
                    },
                    {
                        id:'maxRows',
                        xtype:'numberfield',
                        fieldLabel:'最大行',
                        name:'maxRows',
                        blankText:'该项不能为空...'
                    },
                    {
                        fieldLabel:'键块大小',
                        xtype:'numberfield',
                        name:'keyBlockSize'
                    },
                    {
                        fieldLabel:'数据目录',
                        hidden:true,
                        name:'dataDirectory'
                    },
                    {
                        fieldLabel:'索引目录',
                        hidden:true,
                        name:'indexDirectory'
                    },
                    {
                        fieldLabel:'联合',
                        name:'union',
                        hidden:true
                    },
                    {
                        fieldLabel:'插入方法',
                        xtype:'combo',
                        editable:false,
                        hidden:true,
                        name:'insertMethod',
                        triggerAction:'all',
                        displayField:'label',
                        valueField:'data',
                        queryMode:'local',
                        forceSelection:true,
                        typeAhead:true,
                        store:new Ext.data.Store({
                            fields:['data' , 'label'],
                            data:insertMethodDataArray
                        })
                    },{
                        xtype:'checkboxgroup',
                        fieldLabel:'选项',
                        id:'myism_checks',
                        hidden:true,
                        columns:4,
                        items:[
                            {boxLabel:'校验和',name:'checkSum'},
                            {boxLabel:'延迟写入',name:'delayKeyWrite'}
                        ]
                    },
                    {
                        fieldLabel:'封装键',
                        xtype:'combo',
                        editable:false,
                        hidden:true,
                        name:'packKeys',
                        triggerAction:'all',
                        displayField:'label',
                        valueField:'data',
                        queryMode:'local',
                        forceSelection:true,
                        typeAhead:true,
                        store:new Ext.data.Store({
                            fields:['data' , 'label'],
                            data:packKeysDataArray
                        })
                    }
                ],
                hidden:!flag
            }
        ],
        initCollate:function(collate) {
            var charset = charsetField.getValue();
            if(charset) {
                if(charsetCollateArray[charset]) {
                    collateField.store.loadData(charsetCollateArray[charset]);
                    if(collate) {
                        collateField.setValue(collate);
                    }
                }else {
                    collateField.store.load({
                        params:{charset:charsetField.getValue(),dbtype:now_db_type},
                        callback:function(records) {
                            if(collate) {
                                collateField.setValue(collate);
                            }
                            var arrayData = [];
                            Ext.each(records , function(rec) {
                                arrayData.push(rec.data);
                            });
                            charsetField.setValue(charset);
                            charsetCollateArray[charset] = arrayData;
                        }
                    });
                }
            }
        },
        showHideByEngine:function() {
            Ext.each(tokuDBHideArray , function(row) {
                rForm.findField(row).show();
            });
            if(now_db_type == 'oracle'){
            	engineField.hide();
            	charsetField.hide();
            	collateField.hide();
            }
            var rowFormatField = rForm.findField('rowFormat');
            var v = engineField.getValue();
            if(v != 'TokuDB') {
                rowFormatField.store.loadData(rowFormatDataArray);
                rowFormatField.setValue();
            }
            if(v == 'BLACKHOLE' || v == 'CSV' || v == 'MRG_MYISAM' || v == 'MRG_MYISAM' || v == 'PERFORMANCE_SCHEMA') {
                autoIncrementField.hide();
            }else {
                autoIncrementField.show();
            }
            if(v == 'MRG_MYISAM') {
                unionField.show();
                insertMethodField.show();
            }else {
                unionField.hide();
                insertMethodField.hide();
            }
            if(v == 'MyISAM') {
                checkSumField.show();
                packKeysField.show();
                delayKeyWriteField.show();
                Ext.getCmp('myism_checks').show();
            }else if(v == 'TokuDB') {
                checkSumField.hide();
                packKeysField.hide();
                delayKeyWriteField.hide();
                Ext.getCmp('myism_checks').hide();
                autoIncrementField.hide();
                unionField.hide();
                insertMethodField.hide();
                Ext.each(tokuDBHideArray , function(row) {
                    rForm.findField(row).hide();
                });
                rForm.findField('rowFormat').store.loadData(rowFormatForTokuDBEngine);
                rowFormatField.setValue();
            }else {
                checkSumField.hide();
                packKeysField.hide();
                delayKeyWriteField.hide();
                Ext.getCmp('myism_checks').hide();
            }
        }
    });
    var rForm = form.getForm();
    var engineField = rForm.findField('engine');
    var charsetField = rForm.findField('charset');
    var collateField = rForm.findField('collate');
    var autoIncrementField = rForm.findField('autoIncrement');
    var unionField = rForm.findField('union');
    var insertMethodField = rForm.findField('insertMethod');
    var checkSumField = rForm.findField('checkSum');
    var packKeysField = rForm.findField('packKeys');
    var delayKeyWriteField = rForm.findField('delayKeyWrite');

    var tokuDBHideArray = ['avgRowLength' , 'maxRows' , 'minRows' , 'keyBlockSize'];
    charsetField.on('select' , function() {
        collateField.store.load({
            params:{charset:charsetField.getValue(),dbtype:now_db_type}
        });
    });
    engineField.on('select' , function() {
        form.showHideByEngine();
    });
    return form;
};